<?php
namespace app\tadmin\controller\manage;
use app\tadmin\controller\Controller as BaseController;
use app\common\model\LinkType as LinkTypeModel;
use app\common\model\Link as LinkModel;
use think\facade\Request;
/**
 * 友链管理
 */
class Link extends BaseController {
    /**
     * @param $sitep adsbw的parent_id
     * @param $sites adsbw的ID
     */
    public function index(){
        list($site , $siteinfo) = $this->initData();
        $list = LinkModel::where('linktype_id' , $site)
            ->order('sorts asc')
            ->paginate(15);
        return $this->fetch('index' , compact('site' , 'siteinfo' ,'list'));
    }

    public function add(){
        if (!$this->request->isAjax()) {
            list($site , $siteinfo) = $this->initData();
            return $this->fetch('add', compact('site' , 'siteinfo'));
        }
        $model = new LinkModel;
        $data = $this->postData('link');
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功', url('index',['site'=>$data['linktype_id']]));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    public function edit(){
        if (!$this->request->isAjax()) {
            list($site , $siteinfo) = $this->initData();
            $link = LinkModel::get(input('id'));
            return $this->fetch('edit', compact('site' ,'siteinfo', 'link'));
        }
        $data = $this->postData('link');
        $model = LinkModel::get($data['id']);
        if ($model->edit($data)) {
            return $this->renderSuccess('编辑成功', url('index',['site'=>$data['linktype_id']]));
        }
        $error = $model->getError() ?: '编辑失败';
        return $this->renderError($error);
    }
    /**
     * 公共参数
     */
    private function initData(){
        $site = input('site' , 1);
        $siteinfo = LinkTypeModel::get($site);//友链分类
        return [$site , $siteinfo];
    }

    public function delete($id){
        $model = LinkModel::get($id);
        if (!$model->delete()) {
            return $this->renderError('删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
    
    public function change(){
        $ids = input('ids/a');
        $field = input('field');
        $value = input('value');
        if (LinkModel::where('id','in' , $ids)->update([$field=>$value]) > 0) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError('修改失败');
    }

}